# @Time : 2023/1/6
# @Author : SDAJAVA
from lxml import etree
import urllib.request

# xpath解析
# 解析本地文件
tree = etree.parse('xpath使用本地文件.html')

# 查找ul下的li
li_list = tree.xpath('//ul/li')
print(li_list)
print(len(li_list))  # 判断长度
# 查找所有有ID属性的li
li_id_list = tree.xpath('//ul/li[@id]')
print(li_id_list)
# text()获取标签内容
li_id_text_list = tree.xpath('//ul/li[@id]/text()')
print(li_id_text_list)
# 找到id为l1的li标签,注意@id=“l1”的双引号
li_id_1_text_list = tree.xpath('//ul/li[@id="l1"]/text()')
print(li_id_1_text_list)
# 查找id为l1的li标签的class的属性值
li_id_1_class = tree.xpath('//ul/li[@id="l1"]/@class')
print(li_id_1_class)
# 查询id中包含l的li标签
li_id_l_list = tree.xpath('//ul/li[contains(@id,"l")]/text()')
print(li_id_l_list)
# 查询id的值以l开头的li标签
li_id_start_l = tree.xpath('//ul/li[starts-with(@id,"c")]/text()')
print(li_id_start_l)
# 查询id为l1和class为c1的内容
li_and = tree.xpath('//ul/li[@id="l1" and @class="c1"]/text()')
print(li_and)

li_or = tree.xpath('//ul/li[@id="l1"]/text() | //ul/li[@id="l2"]/text()')
print(li_or)

# 解析服务器响应文件
url = "https://www.baidu.com/"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}

request = urllib.request.Request(url=url, headers=headers)

response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")

html_tree = etree.HTML(content)

result = html_tree.xpath('//input[@id="su"]/@value')
result1 = result[0]
print(result)
print(result1)
